Generator Pattern

Learn about the generator pattern in Golang.

Overview of the generator pattern#

We use a generator pattern to create a sequence of values that we can use to produce an output. A generator is a function that behaves like an iterator. In other words, it’s a function that launches a goroutine that produces data on a channel that it returns.

Created with Fabric.js 3.6.6
Visual representation of generator pattern

1 of 6

Created with Fabric.js 3.6.6
Visual representation of generator pattern

2 of 6

Created with Fabric.js 3.6.6
Visual representation of generator pattern

3 of 6

Created with Fabric.js 3.6.6
Visual representation of generator pattern

4 of 6

Created with Fabric.js 3.6.6
Visual representation of generator pattern

5 of 6

Created with Fabric.js 3.6.6
Visual representation of generator pattern

6 of 6

Let’s break it down into simple words. Once called, the generator function returns a channel containing the produced data. We use goroutines to implement the generators.

Iterating over a generator function

This goroutine (fibonacci) is called a generator in the general case and an iterator when it produces elements of a container. Another goroutine writes to the fibonacci channel. It executes until the channel is closed.

Generator function

Generator with parallelism#

We can add parallelism to generators as well. When the generator task is computationally expensive, we can create multiple goroutines inside it, but we can’t guarantee the order.

Let’s take a simple example of the generator function with multiple goroutines. If we have some expensive functions, we can call this type of function to take advantage of the power of parallelism.

Generator function with parallelism

Execute the code multiple times. Each time, a different output can be observed.

What is a Design Pattern?

Challenge: Write Code with a Generator Pattern